package com.opal.exception;

import com.opal.consts.CommonConst;
import com.opal.consts.WSC;
import com.opal.domain.R;
import com.opal.utils.CommonUtils;
import org.activiti.engine.ActivitiException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class GlobalException {
	
	/**
	 * shiro注解没有权限跳转页面
	 * @return
	 */
	@ExceptionHandler({AuthorizationException.class})
	public String requestAuthorizationException(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (CommonUtils.isAjaxRequest(request)){
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write("{\"statu\":"+ WSC.REQUEST_FORBIDDEN +",\"message\":\"你没有权限！！\"}"); //异步需要自己判断
			return null;
		}else {
			return "/permissionDenied.html";
		}
	}

	/**
	 * 发送方邮件报错
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ArithmeticException.class})
	@ResponseBody
	public R requestActivitiExceptionException(ActivitiException e) {
		if (e.getMessage().matches("Could not send e-mail in execution")){
			return new R(WSC.REQUEST_ERROR, CommonConst.SEONDMAILERROR);
		}else {
			return new R(WSC.REQUEST_ERROR, CommonConst.MAILERROR);
		}

	}

}
